﻿var sys = require('sys');
var http = require('http');
var fs = require('fs');
var url = require('url');
var path = require('path');
var mime = require('./mime');
var util = require('util');

const WEB_CONTENT = './webContent';

var httpServer = http.createServer(function(req, res) {
  var statusCode = 200,
    contentLength,
    _mime = 'text/html';
  if (req.method == 'GET'){
    var url = require('url').parse(req.url, true),
      pathname = url.pathname;
    if (!pathname || pathname == '/') {
      contentLength = writeResponseFromFile('client.html', res);
    } else if (pathname.indexOf('favicon.ico') >= 0) {
      _mime = mime.getMime('.ico');
      res.end();
    } else {
      var extname = path.extname(pathname);
      _mime = mime.getMime(extname);
      contentLength = writeResponseFromFile(pathname, res);
    }
  } else {
    statusCode = 400;
  }

  res.writeHead(statusCode, {
    'Content-Type': _mime,
    'Content-Length': contentLength,
    'Transfer-Encoding': 'chunked'
  });
});

function writeResponseFromFile(filepath, res){
  try {
    var fullpath = path.normalize(path.join(__dirname, WEB_CONTENT, filepath));
    if (!path.existsSync(fullpath)) {
      fullpath = path.normalize(path.join(__dirname, WEB_CONTENT, '404.html'));
    }
    var stat = fs.statSync(fullpath);
    if (/^.+\.mp3$/.test(filepath)) {
      console.log('It\'s mp3 file.');
      var readStream = fs.createReadStream(fullpath);
      // We replaced all the event handlers with a simple call to util.pump()
      util.pump(readStream, res);
    } else {
      fs.createReadStream(fullpath, {
        'flags': 'r',
        'encoding': 'binary',
        'mode': 0666,
        'bufferSize': 4 * 1024
      }).addListener("data", function(chunk){
        res.write(chunk, 'binary');
      }).addListener("end",function() {
        res.end();
      });
    }
    return stat.size;
  } catch (e){
    sys.log(e);
  }
}

module.exports = httpServer;